//
//  WifiManager.m
//  DefendHealth
//
//  Created by 吾诺瀚卓 on 17/3/2.
//  Copyright © 2017年 iMacOne. All rights reserved.
//

#import "WifiManager.h"

#define HOST @"192.168.4.1"
#define PORT @"333"
@interface WifiManager ()<GCDAsyncSocketDelegate>
{
    NSString *_socketStr;
    
}

@end

@implementation WifiManager
//WiFi管理实例
+(WifiManager *)sharedWifiManager
{
    static WifiManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[WifiManager alloc]init];
    });
    return manager;
}
-(instancetype)init
{
    if (self = [super init]) {
        _socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        if ([_socket connectToHost:HOST onPort:[PORT intValue] error:nil]) {
            _socketStr = @"基站连接成功";
        }
        else
        {
            _socketStr = @"基站未连接";
        }
    }
    return self;
}
#pragma mark-写入数据
-(void)writeWifiString:(NSString *)str
{
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [self writeData:data];
}

-(void)writeData:(NSData *)data
{
    [_socket writeData:data withTimeout:-1 tag:0];
    [_socket readDataWithTimeout:-1 tag:0];
}


-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    [_socket readDataWithTimeout:-1 tag:0];
}
#pragma mark-接收数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SOCKETRETURNDATA" object:nil userInfo:@{@"socketData":data}];
    
    [_socket readDataWithTimeout:-1 tag:0];
}

-(void)mangerDisconnect
{
    [_socket disconnect];
}
@end
